package com.zhucan.account.domain.service.impl;

import com.zhucan.account.application.command.cmd.AccountTransferCommand;
import com.zhucan.account.infrastructure.exception.AccountIdCardExistException;
import com.zhucan.account.domain.aggregate.Account;
import com.zhucan.account.infrastructure.db.entity.AccountPO;
import com.zhucan.account.domain.repository.AccountStorage;
import com.zhucan.account.domain.service.AccountService;
import com.zhucan.account.infrastructure.db.AccountRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * author: zhuCan
 * date: 2020/8/4 20:18
 * description:
 */
@Service
@AllArgsConstructor
public class AccountServiceImpl implements AccountService {

  private final AccountStorage storage;

  private final AccountRepository repository;

  @Override
  @Transactional
  public void transfer(Long id, Long targetId, AccountTransferCommand transferCommand) {
    Account source = storage.load(id);
    Account target = storage.load(targetId);

    source.checkAvailability();
    target.checkAvailability();

    source.withdraw(transferCommand.getAmount());
    target.deposit(transferCommand.getAmount());

    storage.save(source);
    storage.save(target);
  }

  @Override
  public void checkIdentityCard(String identityCard) {
    Optional<AccountPO> account = repository.findByIdentityCard(identityCard);

    account.ifPresent(x->{
      throw new AccountIdCardExistException(identityCard);
    });
  }
}
